package com.tinem.platform.web.auth.login.oauth2.ext.wechat;

import com.tinem.platform.module.pojo.co.SessionKeyEnum;
import com.tinem.platform.module.starter.jpa.entity.oauth.Oauth2WechatOpenUserInfo;
import com.tinem.platform.module.starter.jpa.repository.oauth2.Oauth2WechatOpenUserInfoRepository;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import cn.hutool.core.bean.BeanUtil;
import com.baidu.fsg.uid.UidGenerator;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className WechatOpenLoginSuccess
 * @description TODO
 * @site 
 * @company 
 * @create 2020-10-06 10:39
 */
@Component("authenticationSuccessHandler-wechat_open")
public class WechatOpenAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    Oauth2WechatOpenUserInfoRepository oauth2WechatOpenUserInfoRepository;
    @Autowired
    UidGenerator uidGenerator;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        AuthUser authUser = (AuthUser)  request.getSession().getAttribute(SessionKeyEnum.oauth2_userinfo.getKey());
        Oauth2WechatOpenUserInfo oauth2WechatOpenUserInfo = BeanUtil.toBeanIgnoreCase(authUser.getRawUserInfo(),Oauth2WechatOpenUserInfo.class,true);
        oauth2WechatOpenUserInfo.setId(uidGenerator.getUID());
        oauth2WechatOpenUserInfo.setUserId(((LoginUserInfo) authentication.getPrincipal()).getUserId());
        oauth2WechatOpenUserInfoRepository.saveAndFlush(oauth2WechatOpenUserInfo);
        response.sendRedirect("/index.do");
    }
}
